package com.ocom.ugcapi.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayConfigUrl;
import com.ocom.common.dto.GetMealTimeDto;
import com.ocom.common.entity.card.EntityXfMealInfo;
import com.ocom.common.entity.payconfig.EntityXfMealLeave;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.payconfig.GetOrderMealLeaveRequest;
import com.ocom.common.request.payconfig.mealorder.GetOrderPlanMealRequest;
import com.ocom.common.request.ugcapi.UgcOrderedShowRequest;
import com.ocom.common.request.web.ConsTimeConfigOnShowRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtil;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.human.XfUserInfoVo;
import com.ocom.common.vo.payconfig.OrderPlanMealVo;
import com.ocom.common.vo.ugcapi.GzhUserInfo;
import com.ocom.common.vo.ugcapi.UgcOrderedMealVo;
import com.ocom.ugcapi.client.HumanClientService;
import com.ocom.ugcapi.client.PayConfigClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.*;

@Slf4j
@RestController
public class XfMealLeaveController {

    @Autowired
    private PayConfigClientService payConfigClientService;

    @Autowired
    private HumanClientService humanClientService;


    @PostMapping(value = PayConfigUrl.URL_OrderMealLeaveQueryMealLeave)
    public Result queryMealLeave(@RequestBody Map<String, Object> map) {

        GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");

        Long pId = userInfo.getPId();
        UgcOrderedShowRequest request = JSON.parseObject(JSON.toJSONString(map), UgcOrderedShowRequest.class);

        log.info("公众号请假餐段查询 【{}】【{}】", map, request);

        String endDateStr = DateUtil.getStrDate(DateUtil.addDays(DateUtils.strToDate2(request.getMealDate()), request.getDays()), "yyyy-MM-dd");

        // 获取请假信息
        GetOrderMealLeaveRequest getOrderMealLeaveRequest = new GetOrderMealLeaveRequest();
        getOrderMealLeaveRequest.setIsLeave(1);
        getOrderMealLeaveRequest.setComId(request.getUserInfo().getComId());
        getOrderMealLeaveRequest.setBeginDate(request.getMealDate());
        getOrderMealLeaveRequest.setEndDate(endDateStr);
        getOrderMealLeaveRequest.setpId(pId.intValue());
        Result orderMealLeave = payConfigClientService.getOrderMealLeave(getOrderMealLeaveRequest);
        List<EntityXfMealLeave> xfMealLeaves = null;
        Map<String, Object> orderMealLeaveMap = JSON.parseObject(JSON.toJSONString(orderMealLeave.getData()), HashMap.class);
        xfMealLeaves = JSON.parseArray(JSON.toJSONString(orderMealLeaveMap.get("list")), EntityXfMealLeave.class);

        //获取餐段
        Result result1 = payConfigClientService.getCompanyMealNo(request.getUserInfo().getComId());

        if (result1.getCode() != 200 || result1.getData() == null) {
            return ResultUtil.error(ResultEnum.Err_3082);
        }

        List<EntityXfMealInfo> mealInfos = JSON.parseArray(JSON.toJSONString(result1.getData()), EntityXfMealInfo.class);

        List<List<UgcOrderedMealVo>> resMap = new ArrayList<>();
        for (int i = 0; i < request.getDays(); i++) {
            // 时间每天加1
            String dateStr = DateUtil.getStrDate(DateUtil.addDays(DateUtils.strToDate2(request.getMealDate()), i), "yyyy-MM-dd");

            Date dateCu = DateUtils.strToDate2(dateStr);

            List<OrderPlanMealVo> orderPlanMealVos = null;

            // 获取当前时间 大于等于当前时间 获取点餐餐段查询（getOrderPlanMeal）
            if(dateCu.compareTo(DateUtils.strToDate2(DateUtil.getDate()))>=0){
                GetOrderPlanMealRequest getOrderPlanMealRequest = new GetOrderPlanMealRequest();
                getOrderPlanMealRequest.setMealDate(dateStr);
                getOrderPlanMealRequest.setComId(request.getUserInfo().getComId());
                Result<List<OrderPlanMealVo>> result2 = payConfigClientService.getOrderPlanMeal(getOrderPlanMealRequest);
                if(result2.getData()!=null){
                    orderPlanMealVos = result2.getData();
                }
            }
            List<UgcOrderedMealVo> ugcOrderedMealVos = new ArrayList<>();

            for (EntityXfMealInfo entityXfMealInfo : mealInfos) {
                String currMealNo =entityXfMealInfo.getMealNo();
                UgcOrderedMealVo ugcOrderedMealVo = new UgcOrderedMealVo();
                ugcOrderedMealVo.setMealDate(dateStr);
                ugcOrderedMealVo.setMealNo(Integer.valueOf(currMealNo));
                //ugcOrderedMealVo.setStatus(1);
                //ugcOrderedMealVo.setStatusStr("正常");
                ugcOrderedMealVo.setStatus(3);
                ugcOrderedMealVo.setStatusStr("--");
                boolean xfMealStatus=false;
                if(xfMealLeaves!=null && xfMealLeaves.size()>0){
                    for (EntityXfMealLeave xfMealLeave : xfMealLeaves) {
                        if (xfMealLeave.getMealDate().equals(dateStr)
                                && xfMealLeave.getMealNo().equals(Integer.valueOf(currMealNo))
                        ) {
                            ugcOrderedMealVo.setStatus(2);
                            ugcOrderedMealVo.setStatusStr("已请假");
                            xfMealStatus=true;
                            break;
                        }
                    }
                }
                //修改代码逻辑，默认--，存在已请假时赋值已请假，未请假时赋值正常
                if(orderPlanMealVos!=null && orderPlanMealVos.size()>0 && !xfMealStatus){
                    for (OrderPlanMealVo xfMeal : orderPlanMealVos) {
                        if (xfMeal.getMealDate().equals(dateStr)
                                && xfMeal.getMealNo().equals(currMealNo)
                        ) {
                            ugcOrderedMealVo.setStatus(1);
                            ugcOrderedMealVo.setStatusStr("正常");
                            break;
                        }
                    }
                }
                /*
                if(orderPlanMealVos==null || orderPlanMealVos.size() == 0){
                    ugcOrderedMealVo.setStatus(3);
                    ugcOrderedMealVo.setStatusStr("--");
                }
                */
                ugcOrderedMealVos.add(ugcOrderedMealVo);
            }
            resMap.add(ugcOrderedMealVos);
        }

        Map<String, Object> resMap2 = new HashMap<>();

        resMap2.put("list" ,resMap);
        resMap2.put("meal" ,mealInfos);

        log.info("公众号餐段请假查询-返回 【{}】【{}】", request, resMap2);

        return ResultUtil.success(resMap2);
    }

    @PostMapping(value = PayConfigUrl.URL_OrderMealLeaveUpdateMealLeave)
    public Result updateMealLeave(@RequestBody Map<String, Object> map) {
        GzhUserInfo userInfo = (GzhUserInfo) map.get("userInfo");
        String mealDate = (String) map.get("mealDate");
        String mealNo = (String) map.get("mealNo");
        Long comId = userInfo.getComId();
        Long pId = userInfo.getPId();

        ConsTimeConfigOnShowRequest consTimeConfigOnShowRequest =new ConsTimeConfigOnShowRequest();
        consTimeConfigOnShowRequest.setComId(comId);
        consTimeConfigOnShowRequest.setPage(1);
        consTimeConfigOnShowRequest.setSize(50);
        Result result1 = payConfigClientService.GetMealTimeInfo(consTimeConfigOnShowRequest);
        if (result1.getCode() == 200) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(result1.getData()));

            List<GetMealTimeDto> list = JSON.parseArray(JSON.toJSONString(jsonObject.get("list")), GetMealTimeDto.class);

            for (GetMealTimeDto mealTimeDto : list) {
                if (mealTimeDto.getMealNo().equals(mealNo)) {
                    long nowLong = new Date().getTime();

                    //餐段时间
                    Date after = null;
                    try {
                        after = DateUtils.getDate(DateUtils.getStrDate(DateUtils.parseDate(mealDate), "yyyy-MM-dd") + " " + mealTimeDto.getBeginTime(), "yyyy-MM-dd HH:mm:ss");
                    } catch (ParseException e) {
                        continue;
                    }
                    long afterLong = after.getTime() - (mealTimeDto.getBeforeHour() * 3600000);

                    if (nowLong > afterLong) {
                        return ResultUtil.error(ResultEnum.Err_4141);
                    }
                }
                continue;
            }
        }
        
        Result xfUserInfo = humanClientService.getXfUserInfo(comId, pId);
        if (xfUserInfo.getCode() != 200) {
            return xfUserInfo;
        }
        XfUserInfoVo xfUserInfoVo = JSON.parseObject(JSON.toJSONString(xfUserInfo.getData()), XfUserInfoVo.class);
        EntityXfMealLeave xfMealLeave = new EntityXfMealLeave();
        xfMealLeave.setIsLeave((Integer) map.get("isLeave"));
        xfMealLeave.setMealDate(mealDate);
        xfMealLeave.setMealNo(Integer.valueOf(mealNo));
        xfMealLeave.setComId(comId.intValue());
        xfMealLeave.setDeptId(xfUserInfoVo.getDeptId().intValue());
        xfMealLeave.setpName(xfUserInfoVo.getPName());
        xfMealLeave.setpCode(xfUserInfoVo.getPCode());
        xfMealLeave.setpId(xfUserInfoVo.getPId().intValue());
        xfMealLeave.setDeptName(xfUserInfoVo.getDeptName());
        log.info("公众号餐段请假添加-添加 【{}】【{}】", xfMealLeave, xfUserInfoVo);
        return payConfigClientService.setOrderMealLeaveRequest(xfMealLeave);
    }
}
